import "./App.css";
import React, { Component } from "react";
import Header from "./components/Header";
import List from "./components/List";
import Fotter from "./components/Fotter";
//创建并暴露APP组件
export default class APP extends Component {
  //状态在哪里。操作的方法就在那里。
  state = {
    todo: [
      { id: "001", name: "吃饭", done: true },
      { id: "002", name: "睡觉", done: false },
      { id: "003", name: "敲代码", done: true },
    ],
  };
  //在父级中创建方法，给子组件调用，这样后期子组件方法传参调用，父组件就知道，并且可以拿到。
  loadingIput = (dataObj) => {
    //在原理来的基础上获取获取todo的内容，
    const { todo } = this.state;
    //追加一个todo
    const newTodo = [dataObj, ...todo];
    //更新状态
    this.setState({ todo: newTodo });
  };
  //这个是传给item的，祖孙关系
  handleCheck = (id, done) => {
    //获取状态中的todo
    const { todo } = this.state;
    //匹配数值，准备更新
    const newTodos = todo.map((item, index) => {
      if (item.id === id) return { ...item, done: done };
      else return item;
    });
    //更新回去。重新渲染、
    this.setState({ todo: newTodos });
  };
  //删除子组件传来的id
  deletedTodo = (id) => {
    const { todo } = this.state;
    //删除数组中的指定id,利用过滤器来数组数组中不想要的
    const deteleTodos = todo.filter((item) => {
      return item.id !== id;
    });
    this.setState({ todo: deteleTodos });
  };
  //锁定所有的状态
  checkAll = (done) => {
    const { todo } = this.state;
    const newChecked = todo.map((item) => {
      return { ...item, done: done };
    });
    this.setState({
      todo: newChecked,
    });
  };
  //清除所有的已完成任务
  clearDeleted = (done) => {
    const { todo } = this.state;
    const allTodo = todo.filter((item, index) => {
      return !item.done;
    });
    this.setState({ todo: allTodo });
  };
  render() {
    const { todo } = this.state;

    return (
      <div className="todo-container">
        <div className="todo-wrap">
          <Header addPut={this.loadingIput} />
          <List
            todi={todo}
            handleCheck={this.handleCheck}
            deletedTodo={this.deletedTodo}
          />
          <Fotter
            todi={todo}
            checkAll={this.checkAll}
            clearDeleted={this.clearDeleted}
          />
        </div>
      </div>
    );
  }
}
